//
//  APIClient.m
//  BShop
//
//  Created by chenguibang on 2017/8/11.
//  Copyright © 2017年 chenguibang. All rights reserved.
//

#import "APIClient.h"

@implementation APIClient

+ (void)getOSSToken:(void (^)(OSSTaskCompletionSource *, OSSFederationToken *))reult{
    
    NSURL * url = [NSURL URLWithString:@"http://192.168.0.101:8989/api/ossToken"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        [tcs setError:error];
                                                        return;
                                                    }
                                                    [tcs setResult:data];
                                                }];
    
    [sessionTask resume];
    [tcs.task waitUntilFinished];
    if (tcs.task.error) {
      
        if (reult) {
            reult(tcs,nil);
        }
    } else {
        // 返回数据是json格式，需要解析得到token的各个字段
        NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
                                                                options:kNilOptions
                                                                  error:nil][@"credentials"];
        OSSFederationToken * token = [OSSFederationToken new];
        token.tAccessKey = [object objectForKey:@"accessKeyId"];
        token.tSecretKey = [object objectForKey:@"accessKeySecret"];
        token.tToken = [object objectForKey:@"securityToken"];
        token.expirationTimeInGMTFormat = [object objectForKey:@"expiration"];
        NSLog(@"get token: %@", token);
        if (reult) {
            reult(tcs,token);
        }
    }
}



+ (void)loginWith:(LoginRequest *)params{
    
}



+ (void)loginWith:(LoginRequest *)params progress:(void (^)(NSProgress *))downloadProgress success:(void (^)(ApiResponse *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure{
    
    ApiRequest *loginReq = [ApiRequest requestWith:params];
    loginReq.apiInterface = @"login";
    [[APiSessionManager shared] API_GET:loginReq progress:downloadProgress success:success failure:failure];
    
}




@end
